package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.constant.ChatMessageConstant;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.dto.chat.ConversationDto;
import com.example.everying.model.dto.chat.LocationDto;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.vo.chat.ChatMessageVo;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class LocationMessageMessageHandler implements MessageHandler
{

    private static ChatConversationService chatConversationService;
    private static ChatMessagesService chatMessageService;

    @Autowired
    private void setService(
            ChatConversationService chatConversationService,
            ChatMessagesService chatMessageService
    ) {
        LocationMessageMessageHandler.chatConversationService = chatConversationService;
        LocationMessageMessageHandler.chatMessageService = chatMessageService;
    }


    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        log.info("接收到位置信息");
        String userId = WebSocketChatService.getUserId(session);
        String toUserId = message.getString("userId");
        String coord = message.getString("coord"); // 经纬度
        String address = message.getString("address"); // 地址

        // 获取会话id
        ChatConversationEntity chatConversationEntity = chatConversationService.getConversation(userId, toUserId);
        ChatMessagesEntity entity = new ChatMessagesEntity();
        if (chatConversationEntity == null) {
            log.warn("会话不存在");
            return;
        }
        // 保存消息
        entity.setConversationId(chatConversationEntity.getId());
        entity.setFormUserId(userId);
        entity.setToUserId(toUserId);
        entity.setPostMessages("位置信息");
        entity.setMsgStatus(ChatMessageConstant.MESSAGE_STATUS_UNREAD); // 默认未读
        entity.setTime(LocalDateTime.now());
        entity.setMessagesType(ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_LOCATION);
        entity.setType(ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_LOCATION); // 默认为文本消息
        LocationDto locationDto = new LocationDto();
        locationDto.setCoord(coord);
        locationDto.setAddress(address);
        // 序列化为 JSON 字符串
        String jsonLocation = JSON.toJSONString(locationDto);
        entity.setLocationInfo(jsonLocation);
        boolean isSave = chatMessageService.save(entity);
        if (!isSave) {
            log.error("保存消息失败，内容为: {}", "位置信息");
            return;
        }
        // 更新会话最后聊天id
        chatConversationService.updateLastMessageId(chatConversationEntity.getId(), entity.getId(), userId);
        // 构建响应JSON
        JSONObject resJson = buildResponseJson(userId, entity);
        JSONObject toResJson = buildResponseJson(toUserId, entity);


        // 给某个用户发消息
        WebSocketChatService.sendMessageToUserId(toUserId, toResJson.toJSONString());
        WebSocketChatService.sendMessageToUserId(userId, resJson.toJSONString());

        // 在重新发一个列表
        sendChatConversationList(userId);
        sendChatConversationList(toUserId);

    }
    private JSONObject buildResponseJson(String userId, ChatMessagesEntity entity) {
        log.info("发送给{}的消息是{}", userId, entity);
        JSONObject resJson = new JSONObject();
        ChatMessageVo vo = chatMessageService.convertToDTO(entity);
        vo.setSender(entity.getFormUserId().equals(userId));
        resJson.put("type", "locationMessage");
        resJson.put("message", vo);
        resJson.put("conversationId", entity.getConversationId());
        return resJson;
    }

    protected void sendChatConversationList(String userId) {
        List<ConversationDto> conversations = chatConversationService.getUserConversations(userId);
        JSONObject result = new JSONObject();
        result.put("type", "messageList");
        result.put("conversations", conversations);
        int unreadCount = Math.toIntExact(chatMessageService.count(new QueryWrapper<ChatMessagesEntity>().eq("to_user_id", userId).eq("msg_status", ChatMessageConstant.MESSAGE_STATUS_UNREAD)));
        result.put("unreadNum", unreadCount);
        WebSocketChatService.sendMessageToUserId(userId, result.toJSONString());
    }
}
